<?php
/**
 * Created by PhpStorm.
 * User: yandian
 * Date: 16/8/6
 * Time: 16:49
 */

namespace app\common\util\weixin;


use app\common\util\CUrl;

class JsApiTool
{
    public static function getTicket()
    {
        $ticket = S('jsapi_ticket');
        if (empty($ticket)) {
            $JS_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . AccessToken::getAccessToken() . "&type=jsapi";
            $response = CUrl::httpGet($JS_TICKET_URL);
            if (empty($response)) {
                trace('cannot get jsapi ticket', 'error');
                return '';
            }
            $result = json_decode($response, true);
            if ($result['errcode'] != 0) {
                trace('get jspai fail', 'error');
                return '';
            }
            $ticket = $result['ticket'];
            $expireTime = intval($result['expires_in']) - 60;
            S('jsapi_ticket', $ticket, $expireTime > 0 ? $expireTime : 3600);
        }
        return $ticket;
    }

    public static function getSignPackage()
    {
        $jsapiTicket = self::getTicket();
        $url = ccnn_request_url();
        $timestamp = time();
        $nonceStr = self::createNonceStr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId" => AccessToken::getAppId(),
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }


    public static function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

}